/**
 * BBD Service Inc
 * All Rights Reserved @2018
 */
package com.hooview.web.controller;

import com.hooview.utils.AjaxMsg;
import com.hooview.utils.OSSClientUtils;
import com.hooview.web.template.ExecuteTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.QueryParam;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传下载控制器
 *
 * @author gavincook
 * @version $ID: FileController.java, v0.1 2018-05-27 12:32 gavincook Exp $$
 */
@RestController
@RequestMapping("/files")
public class FileController {

    @Autowired
    private ExecuteTemplate executeTemplate;

    @Autowired
    private OSSClientUtils oSSClientUtils;

    /**
     * 上传文件，单个文件。文件的表单项名称为file。
     *
     * @param request 包含单个文件的request
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    AjaxMsg upload(MultipartHttpServletRequest request) throws IOException {
        AjaxMsg result = new AjaxMsg();
        executeTemplate.executeWithoutTransaction(() -> {
            try {
                MultipartFile file = request.getFile("file");
                InputStream in = file.getInputStream();
                result.setDatas(save(in, getExtname(file.getOriginalFilename())));
                in.close();
            } catch (IOException e) {
                throw new IllegalStateException(e);
            }
        }, result);

        return result;
    }

    /**
     * 百度富文本框文件上传
     *
     * @param request 包含多个文件的request
     * @return
     */
    @RequestMapping(value = "/baidu", method = RequestMethod.POST)
    @ResponseBody
    Map<String, Object> uploadBaiduImage(MultipartHttpServletRequest request) {
        AjaxMsg result = new AjaxMsg();
        executeTemplate.executeWithoutTransaction(() -> {
            try {
                MultipartFile file = request.getFile("upfile");
                InputStream in = file.getInputStream();
                Map<String, Object> map = new HashMap<>();
                map.put("url", save(in, getExtname(file.getOriginalFilename())));
                map.put("state", "SUCCESS");
                map.put("name", file.getName());
                map.put("type", getExtname(file.getOriginalFilename()));
                map.put("originalName", file.getOriginalFilename());
                map.put("size", file.getSize());
                result.setDatas(map);
                in.close();
            } catch (IOException e) {
                throw new IllegalStateException(e);
            }
        }, result);

        return (Map<String, Object>) result.getDatas();

    }


    /**
     * 文件下载接口
     *
     * @param filePath 要下载的文件路径
     * @return 返回上传结果, 包含下载文件地址
     */
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    void downloadFile(@QueryParam(value = "filePath") String filePath, HttpServletResponse response) throws IOException {

        OutputStream out = response.getOutputStream();
        File file = new File(filePath);
        if (file.exists()) {
            FileInputStream fileInputStream = new FileInputStream(file);
            StreamUtils.copy(fileInputStream, out);
            response.setContentType(MediaType.IMAGE_PNG_VALUE);
            fileInputStream.close();
        } else {
            response.setStatus(HttpStatus.NOT_FOUND.value());
        }
        out.close();
    }

    /**
     * 保存文件
     *
     * @param in
     * @return
     * @throws IOException
     */
    private String save(InputStream in, String extName) throws IOException {
        String fileName = System.currentTimeMillis() + extName;
        return oSSClientUtils.uploadImg2Oss(in, fileName);
    }

    /**
     * 获取文件后缀名，包括“.”
     *
     * @param fileName
     * @return extName
     */
    public static String getExtname(String fileName) {
        int position = fileName.lastIndexOf(".");
        if (position != -1) {
            return fileName.substring(position);
        }
        return "";
    }
}
